# !/bin/bash
# Script:           install code
# Version:          1.0
# Description:      用来部署
# Email:            litaocheng@gmail.com
# Desc:
#       1,first check out the code from the svn tags
#       2,compile the code with make
#       3,stop the running cupid
#       4,run the new cupid
#       5,install ok

usage() 
{
    echo "-------------------------------------------------"
    echo "usage:"
    echo " ./install.sh -u user -p pass"
    echo ""
    echo "    -u | --username   svn username"
    echo "    -p | --password   svn password"
    echo "-------------------------------------------------"
}

SVN_PATH="http://svn.d.com/ads/engine/code/cupid"
while [ $# -ne 0 ] ; do
    PARAM=$1
    shift
    case $PARAM in
        -u | --username) SVN_USER=$1;shift;;
        -p | --password) SVN_PASS=$1;shift;;
        *) usage;;
    esac
done

if [ -z "$SVN_USER" -o -z "$SVN_PASS" ]; then
    echo "please specify the svn user and password!"
    usage
    exit 1
fi

SVN_AUTH="--username $SVN_USER --password $SVN_PASS"

# checkout the code
co_code()
{
    local INST_PATH="/opt/cupid"
    if !(mkdir -p $INST_PATH) ;then
        echo "create the install dir $INST_PATH error!"
        exit 1
    fi
    
    TAG=$(svn list ${SVN_PATH}/tags $SVN_AUTH | sort | tail -1)
    if ! svn co ${SVN_PATH}/tags/${TAG} $INST_PATH > /dev/null 2>&1; then
        echo "svn checkout code error: $?"
        usage
        exit 1
    fi
    echo $INST_PATH/$TAG
}

#compile the code
compile_code()
{
    TAG=$1
    echo "pwd is " `pwd`
    if ! (cd $TAG && make clean && make); then
        echo "compile cupid code error! $?"
        exit 1
    fi

    if ! (cd ${TAG%/}/mochiweb && make clean && make); then
        echo "compile mochiweb code error! $?"
        exit 1
    fi
    echo "pwd is " `pwd`
}


# stop the running cupid
stop_cupid()
{
    CUPID=$(ps aux | grep 'beam.smp' | grep -v 'grep' | sed -e 's/.*-pa\s//g' | sed -e 's/\s.*//g')
    if [ -n "$CUPID" ]; then
        CUPID=$(dirname $(dirname $CUPID))
        echo "the CUPID path is $CUPID"
        eval "./CUPID/deploy/runctl stop"
        if ! $? ; then
            echo "stop the cupid error"
            exit 1
        fi
    fi
}

# run the new revision
run_cupid()
{
    NEWTAG=$1
    if ! (cd ${NEWTAG%/}/deploy && chmod 600 .erlang.cookie); then
        echo "change the .erlang.cookie mod error!"
        exit 1
    fi

    if ./runctl start && ./runctl status; then
        echo "run the cupid ok "
    fi
}

echo "svn checkout ..."
TAGPATH=$(co_code)
echo "svn checkout ok, the lastest cupid svn tag is: $TAGPATH"

echo "compile the code ..."
compile_code $TAGPATH
echo "compile the code ok"

stop_cupid
run_cupid $TAGPATH

